package cn.mrlong.usbcamera;

import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Surface;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.mrlong.libusbcamera.R;

import cn.mrlong.usbcamera.utils.CountDown;
import cn.mrlong.usbcamera.utils.CountDownInterface;
import cn.mrlong.usbcamera.utils.FileUtils;

import com.serenegiant.usb.CameraDialog;
import com.serenegiant.usb.USBMonitor;
import com.serenegiant.usb.common.AbstractUVCCameraHandler;
import com.serenegiant.usb.encoder.RecordParams;
import com.serenegiant.usb.widget.CameraViewInterface;
import com.serenegiant.usb.widget.UVCCameraTextureView;

import java.io.File;


/**
 */

public class USBCameraActivity extends AppCompatActivity implements CameraDialog.CameraDialogParent, CameraViewInterface.Callback {
    private static final String TAG = "USBCameraActivity";
    private UVCCameraHelper mCameraHelper;
    private UVCCameraTextureView mUVCCameraView;
    private boolean isRequest;
    private boolean isPreview;
    private boolean isDebug = false;
    //设备连接监听器
    private UVCCameraHelper.OnMyDevConnectListener listener = new UVCCameraHelper.OnMyDevConnectListener() {
        @Override
        public void onAttachDev(UsbDevice device) {
            if (mCameraHelper == null || mCameraHelper.getUsbDeviceCount() == 0) {
                showShortMsg("没有检测到可用的USB摄像头");
                return;
            }
            //请求打开摄像头权限
            if (!isRequest) {
                isRequest = true;
                if (mCameraHelper != null) {
                    mCameraHelper.requestPermission(0);
                }
            }
        }

        @Override
        public void onDettachDev(UsbDevice device) {
            // 断开连接
            if (isRequest) {
                isRequest = false;
                mCameraHelper.closeCamera();
                showShortMsg(device.getDeviceName() + "断开连接");
            }
        }

        @Override
        public void onConnectDev(UsbDevice device, boolean isConnected) {
            if (!isConnected) {
                //fail to connect,please check resolution params
                showShortMsg("连接失败，请检查设置的分辨率参数");
                isPreview = false;
            } else {
                isPreview = true;
                showShortMsg("连接中...");
                recordAction();
            }
        }

        @Override
        public void onDisConnectDev(UsbDevice device) {
            showShortMsg("断开连接");
        }
    };
    private Button button;
    private CountDown countDown;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_usbcamera);
        initView();
        initFilePath();

        // 第一步 初始化 UVCCameraHelper
        mUVCCameraView = findViewById(R.id.camera_view);
        //mUVCCameraView = (CameraViewInterface) mTextureView;
        mUVCCameraView.setCallback(this);
        mCameraHelper = UVCCameraHelper.getInstance();
        mCameraHelper.setDefaultFrameFormat(UVCCameraHelper.FRAME_FORMAT_YUYV);
        mCameraHelper.initUSBMonitor(this, mUVCCameraView, listener);


        //进入倒计时
        if (null == countDown)
            countDown = new CountDown(100, 100, new CountDownInterface() {
                @Override
                public void onFinish() {
                    goBackRun();
                }
            });
        countDown.start();


    }

    /**
     * 创建存储文件路径
     */
    private void initFilePath() {
        File fileMp4 = new File(UVCCameraHelper.ROOT_PATH);
        File fileImg = new File(UVCCameraHelper.ROOT_PATH_IMG);
        if (!fileMp4.exists()) {
            fileMp4.mkdirs();
        }
        if (!fileImg.exists()) {
            fileImg.mkdirs();
        }
    }

    private void initView() {
        {

            button = findViewById(R.id.record);
            //录制方法
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mCameraHelper == null || !mCameraHelper.isCameraOpened()) {
                        showShortMsg("摄像头打开失败！");
                        return;
                    }
                    recordAction();
                }
            });
        }
    }


    private void goBackRun() {
        mUVCCameraView.setOnbackRun(true);
        this.moveTaskToBack(true);
        Log.e(TAG, "进入后台");
    }

    @Override
    protected void onStart() {
        super.onStart();
        //第二部 注册usb event broadcast
        if (mCameraHelper != null) {
            mCameraHelper.registerUSB();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        //第三部 反注册USB event broadcast
//        if (mCameraHelper != null) {
//            mCameraHelper.unregisterUSB();
//        }
    }

    /**
     * 录制功能
     */
    private void recordAction() {
        if (!mCameraHelper.isPushing()) {
            String videoPath = UVCCameraHelper.ROOT_PATH + System.currentTimeMillis();
            RecordParams params = new RecordParams();
            params.setRecordPath(videoPath);
            params.setRecordDuration(0); // 设置为0，不分割保存视频文件
            params.setVoiceClose(false);//默认开启录音功能
            mCameraHelper.startPusher(params, new AbstractUVCCameraHandler.OnEncodeResultListener() {
                @Override
                public void onEncodeResult(byte[] data, int offset, int length, long timestamp, int type) {
                    //直接录制视频和音频
                    FileUtils.putFileStream(data, offset, length);
                    // type = 1,h264 video stream
                    // type = 0,aac audio stream
                    Log.e(TAG, "录制中....");
                    Log.e(TAG, "data:" + byteToHex(data));
                }

                @Override
                public void onRecordResult(String videoPath) {
                    Log.i(TAG, "录制地址 = " + videoPath);
                }
            });
            showShortMsg("开始录制...");
            new CountDown(10000, 1000, new CountDownInterface() {
                @Override
                public void onFinish() {
                    stopRecordAtion();
                }
            }).start();
        } else {
            stopRecordAtion();
        }
    }

    public static String byteToHex(byte[] bytes)
    {
        StringBuffer stringBuffer = new StringBuffer();
        for(int i = 0; i < bytes.length; i++)
        {
            String hex = Integer.toHexString(bytes[i]);
            if(hex.length() == 1)
            {
                stringBuffer.append("0" + hex);
            }
            else
            {
                stringBuffer.append(hex);
            }
            if(i > 20)
            {
                break;
            }
        }
        return stringBuffer.toString();
    }
    public void stopRecordAtion() {
        try{
            mUVCCameraView.setOnbackRun(false);
            if (mUVCCameraView != null) {
                mCameraHelper.stopPreview();
            }
            FileUtils.releaseFile();
            if (mCameraHelper != null) {
                mCameraHelper.unregisterUSB();
            }
            // step.4 release uvc camera resources
            if (mCameraHelper != null) {
                mCameraHelper.release();
            }

            showShortMsg("结束录制...");
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            // 第4步 释放 release uvc camera resources
            if (mCameraHelper != null) {
                mCameraHelper.release();
            }
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopRecordAtion();
    }

    private void showShortMsg(String msg) {
        if (isDebug) {
            Log.e(TAG, msg);
            return;
        }
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public USBMonitor getUSBMonitor() {
        return mCameraHelper.getUSBMonitor();
    }

    @Override
    public void onDialogResult(boolean canceled) {
        if (canceled) {
            showShortMsg("取消操作");
        }
    }

    /**
     * 判断是否打开摄像头
     *
     * @return
     */
    public boolean isCameraOpened() {
        return mCameraHelper.isCameraOpened();
    }

    @Override
    public void onSurfaceCreated(CameraViewInterface view, Surface surface) {
        if (!isPreview && mCameraHelper.isCameraOpened()) {
            mCameraHelper.startPreview(mUVCCameraView);
            isPreview = true;
        }
    }

    @Override
    public void onSurfaceChanged(CameraViewInterface view, Surface surface, int width, int height) {

    }

    @Override
    public void onSurfaceDestroy(CameraViewInterface view, Surface surface) {
        if (isPreview && mCameraHelper.isCameraOpened()) {
            mCameraHelper.stopPreview();
            isPreview = false;
        }
    }
}
